package db

import (
	"blockchains-aio/util"
	"time"
)

const (
	INSERT_REPOS       = `insert into t_repos (reposid, name, description, endpoint, username, password, createtime) values(?, ?,?,?,?,?,?)`
	SELECT_REPOS       = `select * from t_repos where reposid=?`
	SELECT_ALL_REPOS   = `select * from t_repos where 1=1 `
	UPDATE_REPOS_BY_ID = `update t_repos set password=?, username=?, endpoint=?, name=?, description=? where reposid=?`
	DELETE_REPOS_BY_ID = `delete from t_repos where reposid=?`
)

func CreateRepos(reposid, name, description, endpoint, username, password string) error {
	createtime := time.Now()

	_, _, err := dbPlus.Exec(INSERT_REPOS, reposid, name, description, endpoint, username, password, &createtime)

	return err
}

func UpdateRepos(password, username, endpoint, name, description, reposid string) error {
	_, _, err := dbPlus.Exec(UPDATE_REPOS_BY_ID, password, username, endpoint, name, description, reposid)
	return err
}

func GetReposById(reposid string) *Repos {
	repos, err := dbPlus.QueryOne(SELECT_REPOS, reposid)

	if err != nil || repos == nil {
		return nil
	}
	id, _ := util.GetInt(util.GetMapValue2(repos, "id", "0"))

	rtn := &Repos{
		Id:          int(id),
		Reposid:     util.GetMapValue2(repos, "reposid", ""),
		Name:        util.GetMapValue2(repos, "name", ""),
		Description: util.GetMapValue2(repos, "description", ""),
		Endpoint:    util.GetMapValue2(repos, "endpoint", ""),
		Username:    util.GetMapValue2(repos, "username", ""),
		Password:    util.GetMapValue2(repos, "password", ""),
		Createtime:  nil,
	}
	//2022-05-13 13:54:40.5049073+08:00

	return rtn
}

func GetAllRepos() []Repos {
	rs, err := dbPlus.QueryResultSet(SELECT_ALL_REPOS)

	if err != nil {
		return nil
	}
	rsLen := rs.Length()
	var reposArray []Repos

	for index := 0; index < rsLen; index++ {
		id, _ := rs.GetIntByName(index, "id")
		reposid, _ := rs.GetStringByName(index, "reposid")
		name, _ := rs.GetStringByName(index, "name")
		description, _ := rs.GetStringByName(index, "description")
		endpoint, _ := rs.GetStringByName(index, "endpoint")
		username, _ := rs.GetStringByName(index, "username")
		password, _ := rs.GetStringByName(index, "password")

		reposArray = append(reposArray, Repos{
			Id:          int(*id),
			Reposid:     *reposid,
			Name:        *name,
			Description: *description,
			Endpoint:    *endpoint,
			Username:    *username,
			Password:    *password,
			Createtime:  nil,
		})
	}

	return reposArray
}

func DelReposById(reposid string) error {
	_, _, err := dbPlus.Exec(DELETE_REPOS_BY_ID, reposid)
	return err
}
